<template>
    <el-form :model="form" :disabled="true" label-width="auto" class="formContent">
      <el-row>
        <el-col :span="24">
          <el-form-item label="收货人:">
            <span>{{ form.sendName }}</span>
          </el-form-item>
          <el-form-item label="收货电话:">
            <span>{{ form.sendPhone }}</span>
          </el-form-item>
          <el-form-item label="收货地址:">
            <span>{{ form.userAddressInfo }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  <el-divider style="margin-top: -5px;font-size: 12px;" content-position="center">商品信息</el-divider>
  <div>
    <el-button style="margin-top: -20px; margin-bottom: 5px;" type="warning" @click="toggleSelection">全选/取消</el-button>
    <el-table :data="form.collageLogisticsResultList" border max-height="700px" v-loadmore="handleScroll">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="cardCollageName" label="拼团信息" width="410" >
        <template #default="scope">
          <div>
            <el-row :gutter="24" style="align-items: center;">
              <el-col :span="8">
                <image-preview :src="scope.row.collageImagePath" width="130px" height="100px"></image-preview>
              </el-col>
              <el-col :span="16">
                <span style="color: #945dd9;">名称:  {{ scope.row.cardCollageName }} </span>
              </el-col>
            </el-row>
          </div>
          <div>
            <span style="color: #0887cb;">编码:  {{ scope.row.collageCode }} </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="gainCardStatus" label="订单信息" width="1000" align="center">
        <template #default="scope">
          <el-table :data="scope.row.logisticsDetailResultList" :show-header="true" border :ref="'tableRef'+scope.$index" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column prop="cardOrderNumber" label="订单编号" align="center" />
            <el-table-column label="卡密" align="center" class-name="small-padding fixed-width" >
              <template #default="scopecarmi">
                <div v-if = "scopecarmi.row.carmiInfoList != null && scopecarmi.row.carmiInfoList != '' && scopecarmi.row.carmiInfoList != undefined">
                  <p style="margin-top: -3px" v-for="(item, index) in scopecarmi.row.carmiInfoList" :key="index">
                    {{ item }}<br v-if="index < scopecarmi.row.carmiInfoList.length - 1">
                  </p>
                </div>
                <div v-else>
                  <el-button type="text" @click="viewGainCard(scopecarmi.row)">查看卡密</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="userInviteCode" label="玩家号" align="center"  width="80"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
              <template #default="scope1">
                <div style="margin-top: 5px">
                  <el-button
                             type="text" icon="CreditCard" @click="viewGainCard(scope1.row)">查看中卡</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
    </el-table>
    <el-divider/>
    <el-form :model="deliverForm" label-width="auto" >
      <el-row :gutter="20" style="margin-top: 10px">
        <el-col :span="10">
          <el-form-item label="物流公司" prop="expressageComCode">
            <el-select v-model="deliverForm.expressageComCode" style="width: 100%" clearable filterable @change="chooseComCode" :no-data-text="noDataText">
              <el-option v-for="item in expressageInfoListers" :key="item.id" :value="item.expressageComCode"
                         :label="item.expressageCompany"></el-option>
              <div class="selectMore" v-if="more == '0' " @click.stop="loadMore">点击加载更多</div>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="快递单号" prop="expressageNumber">
            <el-input v-model="deliverForm.expressageNumber" placeholder="请输入快递单号" style="width: 100%"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div align="center">
        <el-button type="primary" @click="sendCardExpressage" >发 货</el-button>
      </div>
    </el-form>
  </div>

  <!-- 查看中卡对话框 -->
  <el-dialog title="查看中卡" v-model="openGainCard.visible" width="1000px" append-to-body>
    <el-table v-loading="loading" :data="reportVoList">
      <el-table-column label="卡密信息" align="center" prop="carmiInfo" />
      <el-table-column label="正面图" align="center" prop="frontImagePath" >
        <template #default="scope">
          <image-preview :src="scope.row.frontImagePath" width="100px" height="120px"></image-preview>
        </template>
      </el-table-column>
      <el-table-column label="反面图" align="center" prop="reverseImagePath">
        <template #default="scope">
          <image-preview :src="scope.row.reverseImagePath"  width="100px" height="120px"></image-preview>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="totalReport > 0" :total="totalReport" v-model:page="gainCardParams.pageNum" v-model:limit="gainCardParams.pageSize" @pagination="getGainCardList" />
  </el-dialog>
</template>

<script lang="ts" setup>
import {
  getGainCardCarmiInfo, queryExpressageInfoList,
  sendCardOrdersLogisticsExpressage, sendLogisticsExpressage
} from '@/api/system/orderLogistics';
import { ElForm } from 'element-plus';
import { ElTable, ElTableColumn, ElButton } from 'element-plus';
import { ref } from 'vue';
import {
  LogisticsResult,
  OrderLogisticsVO,
  LogisticsDetailResult,
  CardOpenReportVo
} from '@/api/system/orderLogistics/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(['subSucess'])
const {sys_yes_no} = toRefs<any>(
  proxy?.useDict('sys_yes_no')
);

const openGainCard = reactive<DialogOption>({
  visible: false,
  title: ''
});
const sourceDataCarmiList = ref([]);
const total = ref();
const buttonLoading = ref(false);
const reportVoList = ref<CardOpenReportVo[]>([]);
const totalReport = ref();
const logisticsId = ref();
const form = ref<LogisticsResult>({});
const tableRef = ref(null)
const expressageInfoListers = ref([]);
const loading = ref(true);
const noDataText = ref('暂无更多数据');
const more = ref('0');
const ids = ref([]);
const props = defineProps({
  logisticsId: {
    type: String,
    default: ''
  },
});

const gainCardParams = reactive({
  pageNum: 1,
  pageSize: 10,
  cardOrderLogisticsId: undefined,
});

const deliverForm = reactive({
  expressageNumber: undefined,//快递单号
  expressageCompany: undefined,// 物流公司
  expressageComCode: undefined, // 物流公司编码
  logisticsIds: [],
})

const getInfo = async (id: string| number) => {
  buttonLoading.value = true;
  const res = await sendCardOrdersLogisticsExpressage(id);
  if(res.code == 200) {
    form.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
  buttonLoading.value = false;
  getExpressageInfoListers();
}

const loadMore = async () => {
  more.value = '1';
  deliverForm.expressageComCode = '';
  noDataText.value = '正在加载...';
  getExpressageInfoListers();
}

const getExpressageInfoListers = async () => {
  expressageInfoListers.value = [];
  const res = await queryExpressageInfoList(more.value);
  expressageInfoListers.value = res.data;
  if(res.data.length == 0) {
    noDataText.value = '暂无更多数据';
  }
}

const viewGainCard = (row?: any) => {
  openGainCard.visible = true;
  gainCardParams.cardOrderLogisticsId = row.logisticsId;
  getGainCardList();
}


const getGainCardList = async () => {
  loading.value = true;
  const res = await getGainCardCarmiInfo(gainCardParams);
  if(res.code == 200) {
    reportVoList.value = res.rows;
    totalReport.value = res.total;
  } else {
    proxy?.$modal.msgError("查询失败");
  }
  loading.value = false;
}

watch(
  () => props.logisticsId,
  (val) => {
    // 在这里添加你需要执行的逻辑
    if (val) {
      getInfo(props.logisticsId);
    }
  },
  { immediate: true, deep: true } // 立即执行一次回调
);
const toggleSelection = () => {
  // console.log(tableRef)
  // console.log(proxy?.$refs.tableRef);
  // form.value.collageLogisticsResultList
  form.value.collageLogisticsResultList.forEach((item: any,index: number) => {
    // item.flag = true;
    // console.log('index :>> ', index);
    proxy?.$refs['tableRef'+index].toggleAllSelection();
    // console.log(proxy?.$refs['tableRef'+index]);
  })
  // tableRef.value.toggleAllSelection();
  // tableRef.value.clearSelection();
  // console.log(tableRef.value.data)
};

const chooseComCode = () => {
  deliverForm.expressageComCode;
  expressageInfoListers.value.forEach((item: any) => {
    if(item.expressageComCode == deliverForm.expressageComCode) {
      deliverForm.expressageCompany = item.expressageCompany;
    }
  })
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: LogisticsDetailResult[]) => {
  // console.log(selection)
  let arr: any[]  = []
  form.value.collageLogisticsResultList.forEach((item: any,index: number) => {
    // item.flag = true;
    // console.log('index :>> ', index);
    let itemRef:ElTable  = proxy?.$refs['tableRef'+index]
    let newArr = itemRef.getSelectionRows()
    // console.log(newArr);
    arr.push(...newArr)
    // console.log(proxy?.$refs['tableRef'+index]);
  })
  // console.log(arr);

  ids.value = arr.map(item => item.logisticsId);

  // single.value = selection.length != 1;
  // multiple.value = !selection.length;
}

const sendCardExpressage = async () => {
  deliverForm.logisticsIds = ids.value;
  const res = await sendLogisticsExpressage(deliverForm);
  if(res.code == 200) {
    emit('subSucess')
  }
};

</script>

<style lang="scss" scoped>
::v-deep(.el-divider__text){
  font-size:15px;
  font-weight:bold;
}
.selectMore{
  font-size: 14px;
  padding: 10px 15px;
  text-align: center;
  cursor: pointer;
  color: var(--el-text-color-primary);
}
</style>
